var gBlogObject = null;
var gTempBlogObject = new Object();
var gPffAccountTimeOut = [];
var gTempFeedback = null;
var gAutoReturn = false;
var gSelectedBlogs = [];
var gShowSpacesHelp = false;
var gPffDebugTemp = [];

var gIsCustomBlog = false;

window.addEventListener('load', onLoad, false);

var scribefireAccountWizard = { };

function configureManually() {
	gIsCustomBlog = true;
	goTo('login-custom');
}

function onClose(){
    try {
        window.opener.getScribefireWindow().performancingUI.reLoadBlogs();
	} catch (e) {
		window.opener.setTimeout(function () {
		        try { performancingUI.reLoadBlogs(); } catch (e) { }
		    }, 1000);
	}
	
    return true;
}

function onLoad(){
    loadPerFormancingUtil(true);
	SCRIBEFIRE_DB.load();
}

function onAutoNext(){
    if(!gAutoReturn){
        doCheckURL();
        return false;
    }else{
        return true
    }
}

function doCheckURL(){
    var isValid = checkURL();
    var autoDetectDeck = document.getElementById("autodetect-deck");
    if(isValid){
        enableNext();
        autoDetectDeck.selectedIndex = "2";
    }else{
        //autoDetectDeck.selectedIndex = "3";
        doServerAPICheck();
    }
    gAutoReturn = true;
}

function goTo( aWizard ){
    document.getElementById('performancing-account-wizard').goTo(aWizard);
}

function tryAgain(){
    var autoDetectDeck = document.getElementById("autodetect-deck");
    autoDetectDeck.selectedIndex = "0";
}

function checkURL(){
    var isStandard = checkForStandardURL();
    var autoDetectDeck = document.getElementById("autodetect-deck");
    autoDetectDeck.selectedIndex = "1";
    if(isStandard){
        document.getElementById('performancing-account-wizard').getPageById('start').next = "start2";
        enableNext();
        return true;
    }
}

function checkForStandardURL(){
    var theDomain = document.getElementById("blog-url").value;
    var serviceList = document.getElementById("performancing-blogservice-list");
    //var customServiceList = document.getElementById('performancing-blogservice-custom-list');
    var theSelectedBlogIndex = null;
    var isStandard = false;
	gShowSpacesHelp = false;
    if(theDomain.search(/\.typepad\.com/) != -1 || theDomain.search(/\.blogs\.com/) != -1){
        theSelectedBlogIndex = "1";
        isStandard = true;
    }else if(theDomain.search(/livejournal\.com/) != -1){
        theSelectedBlogIndex = "2";
        isStandard = true;
    }else if(theDomain.search(/spaces\.msn\.com/) != -1 || theDomain.search(/spaces\.live\.com/) != -1){
        theSelectedBlogIndex = "3";
		gShowSpacesHelp = true;
        isStandard = true;
    }else if(theDomain.search(/performancing\.com/) != -1){
        theSelectedBlogIndex = "4";
        isStandard = true;
    }else if(theDomain.search(/jeeran\.com/) != -1){
        theSelectedBlogIndex = "5";
        isStandard = true;
    }
    else if (theDomain.search(/tumblr\.com/) != -1) {
		theSelectedBlogIndex = "6";
		isStandard = true;
	}
	else if (theDomain.search(/splinder\.com/) != -1) {
		theSelectedBlogIndex = "7";
		isStandard = true;
	}
	else if (theDomain.search(/insanejournal\.com/) != -1) {
		theSelectedBlogIndex = "8";
		isStandard = true;
	}
	else if (theDomain.search(/xanga\.com/) != -1) {
		theSelectedBlogIndex = "9";
		isStandard = true;
	}
	else if (theDomain.search(/posterous\.com/) != -1) {
		theSelectedBlogIndex = 10;
		isStandard = true;
	}
	
    if(isStandard){
        serviceList.selectedIndex = theSelectedBlogIndex;

		document.getElementById('performancing-account-wizard').getPageById('start').next = "start2";
		
		var autoDetectDeck = document.getElementById("autodetect-deck");
	    autoDetectDeck.selectedIndex = "1";
	
		goTo("login");

        return true;
    }else{
        return false;
    }
}

//Check to see if we need to show the custom settings window
function checkForCustom(){
    var serviceList = document.getElementById('performancing-blogservice-list');
    var aService = serviceList.selectedItem.value;
    if( aService.match("_cust") ){
         //document.getElementById('performancing-account-wizard').advance("login-custom");
         document.getElementById('performancing-account-wizard').getPageById('start2').next = "login-custom";
         return true;
    }
    return true;
}

function tryServiceLogin(){
	if (!gIsCustomBlog) {
		var serviceList = document.getElementById('performancing-blogservice-list');
		var appKey = serviceList.selectedItem.getAttribute("apikey");
		var apiUrl = serviceList.selectedItem.getAttribute("apiurl");
	}
	else {
		var serviceList = document.getElementById('performancing-blogservice-custom-list');
		var appKey = document.getElementById('custom-appkey').value;
		var apiUrl = document.getElementById('custom-apiurl').value;
	}
	
	var blogType = serviceList.selectedItem.value;
	var apiType = serviceList.selectedItem.getAttribute("api");
	var username = document.getElementById('username').value;
	var password = document.getElementById('password').value;
	
	if(username != "" && password != ""){
		document.getElementById("login-error-msg").hidden = true;
		
		var isAtom = false;
		var serviceObject = null;
		
		switch(apiType){
			case "s_mt":
				serviceObject = new perFormancingMovableTypeAPI();
			break;
			
			case "s_blogger":
				serviceObject = new perFormancingBloggerAPI();
			break;
			
			case "s_metaweblog":
				serviceObject = new performancingMetaweblogAPI();
			break;
			
			case "s_tumblr":
				serviceObject = new performancingTumblrAPI();
				isAtom = true;
			break;
			
			case "s_posterous":
				serviceObject = new performancingPosterousAPI();
				isAtom = true;
			break;
			
			// Start Custom/Standard API's
			
			case "atom": //https://blogger.com/atom
				serviceObject = new perFormancingAtomAPI();
				isAtom = true;
			break;
			
			case "atom_blogger": //https://blogger.com/ Beta
				serviceObject = new perFormancingBloggerAtomAPI();
				isAtom = true;
			break;
			
			case "mt":
				serviceObject = new perFormancingMovableTypeAPI();
			break;
			
			case "blogger":
				serviceObject = new perFormancingBloggerAPI();
			break;
			
			case "metaweblog":
				serviceObject = new performancingMetaweblogAPI();
			break;
			
			default:
				alert(performancingUI.getLocaleString('awnoservicechosen'));
				return false;
			break;
		}
		
		apiUrl = apiUrl.replace("_USER_NAME_", username);
		
		// Blogger
		serviceObject.doSetup();
		serviceObject.init(blogType, appKey, apiUrl, null, null, username,  password, false  );
		
		// Setup temp object
		gTempBlogObject.blogtype = blogType;
		gTempBlogObject.blogapi = apiType;
		gTempBlogObject.apiurl = apiUrl;
		gTempBlogObject.appkey = appKey;
		
		var xmlRequest = serviceObject.getUsersBlogs();
		
		if (xmlRequest && !isAtom){
			performancing_xmlcall.sendCommand(apiUrl, xmlRequest, 'accountwizard', "", "", performancing_xmlcall.processData);
			setLoginTimeOut();
		}
		
		return true;
	}
	else {
		document.getElementById("login-error-msg").hidden = false;
		return false;
	}
}

function tryServiceSelection(){
    var serviceList = document.getElementById('performancing-wizard-blog-list');
    
    if (serviceList.selectedCount > 0) {
            gSelectedBlogs = serviceList.selectedItems;
            return true;
    }
    else{
        var localeString = performancingUI.getLocaleString('selectablog', []);
        alert(localeString);
        return false;
    }
}


function disableNext(){
    document.getElementById('performancing-account-wizard').getButton('next').disabled = true;
    return true;
}

function enableNext(){
	if (gShowSpacesHelp) document.getElementById("spaces-help").style.display = '';
	else document.getElementById("spaces-help").style.display = 'none';
	
    document.getElementById('performancing-account-wizard').getButton('next').disabled = false;
    return true;
}

function disableBack(){
    document.getElementById('performancing-account-wizard').getButton('back').disabled = true;
    return true;
}

function enableBack(){
    document.getElementById('performancing-account-wizard').getButton('back').disabled = false;
    return true;
}

function processReturnData(theObject, isAtom, theXML){
	document.getElementById("faultString").collapsed = true;
	
    clearLoginTimeOut();

    var isError = true;

	if ("faultString" in theObject) {
		var node = document.getElementById("faultStringContent");
		
		while (node.firstChild) node.removeChild(node.firstChild);
		document.getElementById("faultStringContent").appendChild(document.createTextNode(theObject.faultString));
		
		document.getElementById("faultString").collapsed = false;
	}
    else if(theObject.length != null){
        isError = false;

        gBlogObject = theObject;
        clearListOut();
        var tempArray = [];
        for(j = 0; j < gBlogObject.length; j++){
            var blogName = gBlogObject[j].blogName; 
            var blogURL = gBlogObject[j].url;
            var theGUID = newGuid();
            var theBlogID = gBlogObject[j].blogid;

			if ("xmlrpc" in gBlogObject[j]) {
				var theBlogAPI = gBlogObject[j].xmlrpc;
			}
			else {
				var theBlogAPI = gTempBlogObject.apiurl;
			}
			
            addItemToList(blogName, blogURL, j, theGUID, theBlogID, theBlogAPI );
        }

        var serviceList = document.getElementById('performancing-wizard-blog-list');
       
        if (serviceList.getRowCount() == 0){
        	isError = true;
        }
        else {
	        if( serviceList.selectedCount == 0) {
        	    serviceList.invertSelection();
       		 }
        }
    }
    
    if(!isError){
        //document.getElementById('performancing-account-wizard').getPageById('login').next = "finish";
        document.getElementById('performancing-account-wizard').advance("success");
        return true;
    }else{
         //document.getElementById('performancing-account-wizard').getPageById('login').next = "login-error";
         document.getElementById('performancing-account-wizard').advance("login-error");
         return true;
    }
}

function gotoLoginPage(){
    document.getElementById('performancing-account-wizard').goTo("login");
    return false;
}

/*
// Original function by Lewis E. Moten III
// Terms of Agreement:   
// By using this code, you agree to the following terms...   
// 1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
// 2) You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
// 3) You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
// 4) You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
*/

function newGuid() { 
    var g = ""; 
    for(var i = 0; i < 32; i++){
        g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : ""); 
    }
    return g;
}
////////////////////

function saveBlogToSprefs(){
    var result = false;
    var tempGUID = [];
    //gSelectedBlogs
    if(gSelectedBlogs.length > 0){
        
        for(var i=0; i < gSelectedBlogs.length; i++){
            //
            var theBlogName = gSelectedBlogs[i].getAttribute('blogname');
            var theGUID = gSelectedBlogs[i].getAttribute('blogguid');
            var theURL = gSelectedBlogs[i].getAttribute('blogurl');
            var theBlogID = gSelectedBlogs[i].getAttribute('blogid');
			var theAPIURL = gSelectedBlogs[i].getAttribute("blogapi");
            
            var theBlogType = gTempBlogObject.blogtype;
            var theBlogAPI = gTempBlogObject.blogapi;
            var theAppKey = gTempBlogObject.appkey;
            
            var theUserName = document.getElementById('username').value;
            var thePassWord = document.getElementById('password').value;
            var useBoolean = document.getElementById('useBooleanForPublish').checked;
            
            //First 3 are for legacy support (v1.0)
            if(theBlogType == "blogger_com" || theBlogType == "atom_cust" || theBlogType == "livejournal_atom_com" || theBlogType == "s_atom" || theBlogType == "atom" || theBlogType == "__atom_blogger"){
                theAPIURL = gBlogObject[i].url;
            }                                                                                                                 
            
            var theAppKey = gTempBlogObject.appkey;
            
            saveBlog(theBlogName, theBlogType, theAppKey, theUserName, theAPIURL, theGUID, theURL, theBlogID, theBlogAPI, useBoolean  );
            
            //Now save the username and password based on username and url
            var addedUser = gPerformancingUtil.usermanagment.storeLoginDetails(theUserName, thePassWord, theURL);
        }
        
        if(!addedUser){
                var localeString = performancingUI.getLocaleString('awerrorsavinglogininfo', []);
                alert(localeString);
        }
        
        document.getElementById('performancing-account-wizard').getButton('back').disabled = true;
    }
}

function saveBlog(theBlogName, theBlogType, theAppKey, theUserName, theAPIURL, theGUID, theURL, theBlogID, theBlogAPI, useBoolean ){
	var db = SCRIBEFIRE_DB.getDB();
	
	var insert = db.createStatement("INSERT INTO "+SCRIBEFIRE_DB.blogsTable+" (name, type, key, username, api, guid, url, blogId, useBoolean) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)");
	insert.bindUTF8StringParameter(0, theBlogName);
	insert.bindUTF8StringParameter(1, theBlogType);
	insert.bindUTF8StringParameter(2, theAppKey);
	insert.bindUTF8StringParameter(3, theUserName);
	insert.bindUTF8StringParameter(4, theAPIURL);
	insert.bindUTF8StringParameter(5, theGUID);
	insert.bindUTF8StringParameter(6, theURL);
	insert.bindUTF8StringParameter(7, theBlogID);
	insert.bindUTF8StringParameter(8, useBoolean);
	insert.execute()
	
	SCRIBEFIRE_DB.closeDB(db);
}

function clearListOut(){
    var list=document.getElementById('performancing-wizard-blog-list');
    while(list.getRowCount() > 0){
        list.removeItemAt( list.getRowCount() - 1);
    }
}

function addItemToList(theBlogName, theURL, number, theGUID, theBlogID, theBlogAPI){
    var list = document.getElementById('performancing-wizard-blog-list');
    var item = document.createElement('listitem');
    item.setAttribute('id', 'blog-' + number);
    item.setAttribute('blogname', theBlogName);
    item.setAttribute('blogguid', theGUID);
    item.setAttribute('blogurl', theURL);
    item.setAttribute('blogid', theBlogID);
    item.setAttribute("blogapi", theBlogAPI);
    
    var itemCell = document.createElement('listcell');
    itemCell.setAttribute('label', theBlogName);
    item.appendChild(itemCell);
    
    var itemCell2 = document.createElement('listcell');
    itemCell2.setAttribute('label', theURL);
    item.appendChild(itemCell2);
    
    //Append the elements
    list.appendChild(item);
    //sizeToContent();
}


function onCustomListClick(){
    var customServiceList = document.getElementById('performancing-blogservice-custom-list');
    var aCustomServiceAPI = customServiceList.selectedItem.getAttribute("apiurl");
    var customAPIBox = document.getElementById('custom-apiurl');
    customAPIBox.value = aCustomServiceAPI;
    
    if(customServiceList.selectedItem.value == 'roller_cust'){
        var localeString = performancingUI.getLocaleString('awrollersupport', []);
        alert(localeString);
    }
    if( customServiceList.selectedItem.getAttribute("useBoolean") == 'true'){
        document.getElementById('useBooleanForPublish').checked = true;
    }else{
        document.getElementById('useBooleanForPublish').checked = false;
    }
}

function setLoginTimeOut(){
    gPffAccountTimeOut = window.setTimeout(onLoginTimeOut, 15000);
}

function clearLoginTimeOut(){
    window.clearTimeout(gPffAccountTimeOut);
}

function onLoginTimeOut(){
	alert(performancingUI.getLocaleString("accountWizardLoginTimeout"));
	goTo('login');
}

function doServerAPICheck(){
    var theDomain = document.getElementById("blog-url").value;
    
    //Make sure it's a valid URL:
    if( theDomain.search("http://") == "-1" && theDomain.search("https://") == "-1"){
        theDomain = "http://" + theDomain;
    }

    var theCall = new PffXmlHttpReq(theDomain, "GET", null, false, null, null);
    
    theCall.onResult = function( aText, aXML ){
        processAutoDetectPage(aText, 'plain');
    }
    theCall.onError = function (aStatusMsg, Msg) {
    }

    theCall.prepCall();
    theCall.makeCall();
}

function processAutoDetectPage(theXMLData, dataFormat){
    var autoDetectDeck = document.getElementById("autodetect-deck");

    try {
        if (dataFormat == 'plain'){
			theResult = findServiceFromLinkTag(theXMLData);
			return;
        }
		else if (dataFormat == 'xml'){
            theResult = findServiceFromApiTag( theXMLData );
        }
		else if (dataFormat == 'parsed' ) {
			theResult = theXMLData;
		}
		else {
			theResult = [false, null, null];
		}
		
        if(theResult[0]){
            var customServiceList = document.getElementById('performancing-blogservice-custom-list');
            var theSelectedBlogIndex = null;
            var theAPI = theResult[1];
            var theURL = theResult[2];
            
            switch(theAPI){
                case "wordpress":
                    customServiceList.selectedIndex = "0";
                    break;
                    
                case "blogger":
                    break;
                
                case "blogger_beta":
                    customServiceList.selectedIndex = "6";
                    break;
                
                case "metaweblog":
                    customServiceList.selectedIndex = "5";
                    break;
                    
                case "movabletype":
                    customServiceList.selectedIndex = "1";
                    break;
            }

            var serviceList = document.getElementById('performancing-blogservice-list');
            serviceList.selectedItem.value = "_custom"
            onCustomListClick();
            var custAPIURL = document.getElementById('custom-apiurl');

            custAPIURL.value = theURL;
            document.getElementById('performancing-account-wizard').getPageById('start').next = "login-custom";
            document.getElementById('performancing-account-wizard').advance('login-custom');
            document.getElementById('performancing-account-wizard').getPageById('login-custom').back = "start";
            enableNext();
            autoDetectDeck.selectedIndex = "0";
        }
		else{
            autoDetectDeck.selectedIndex = "3";
        }
    } catch(e) {
        autoDetectDeck.selectedIndex = "3";
    }
}

function findServiceFromLinkTag(theXMLData){
	gPerformancingUtil.convertTextToHTML(theXMLData, findServiceFromLinkTagDOM);
}

function findServiceFromLinkTagDOM(text, notUsed, doc) {
	var linkTags = doc.getElementsByTagName("link");
	
	for (var i = 0; i < linkTags.length; i++) {
		var rel = linkTags[i].getAttribute("rel");
		var type = linkTags[i].getAttribute("type");
		var title = linkTags[i].getAttribute("title");
		var href = linkTags[i].getAttribute("href");
		
		if (rel && type && href && rel == 'service.post' && type == 'application/atom+xml' && href.indexOf("posts/") != -1) {
			return processAutoDetectPage( [true, "blogger_beta", href], 'parsed' );
		}
		else if (rel && href && rel == 'pingback') {
			return processAutoDetectPage( [true, 'wordpress', href], 'parsed' );
		}
		else if (title && href && title == 'RSD') {
			return checkForRSD(href);
		}
	}
	
	return processAutoDetectPage( [ false, null, null ], 'parsed');
}

function checkForRSD(aURL){
    var theCall = new PffXmlHttpReq(aURL, "GET", null, false, null, null);
    
    theCall.onResult = function( aText, aXML ){
        processAutoDetectPage(aXML, 'xml');
    };

    theCall.onError = function (aStatusMsg, Msg) {
		// This will result in the "cannot auto-detect" error being shown
		processAutoDetectPage();
    };

    theCall.prepCall();
    theCall.request.setRequestHeader("Content-Type", "text/xml");
    theCall.makeCall();
    theCall.request.overrideMimeType('text/xml');
}

function findServiceFromApiTag(theXMLData) {
	try {
		var engines = theXMLData.getElementsByTagName("engineName");
		
		if (engines.length > 0) {
			var engine = engines[0];
			
			if (engine.textContent == 'TypePad') {
				document.getElementById("performancing-blogservice-list").selectedIndex = 1;
				document.getElementById('performancing-account-wizard').getPageById('start').next = "start2";
				
				var autoDetectDeck = document.getElementById("autodetect-deck");
			    autoDetectDeck.selectedIndex = "1";
			
				goTo("login");
				return;
			}
		}
		var apis = theXMLData.getElementsByTagName("api");
		
		for (var i = 0; i < apis.length; i++) {
			var name = apis[i].getAttribute("name").toLowerCase();
			var apiLink = apis[i].getAttribute("apiLink");
			
			if(name=="blogger") {
				return [true, "blogger", apiLink];
			}
			else if(name=="metaweblog") {
				return [true, "metaweblog", apiLink];
			}
			else if(name=="movabletype" || name == "movable type") {
				return [true, "movabletype", apiLink];
			}
			else if (name=="wordpress") {
				return [true, "wordpress", apiLink];
			}
		}
	} catch(e) { }
	
	return [false, "error"];
}